package com.qall.util;


import com.alibaba.dubbo.config.ApplicationConfig;
import com.alibaba.dubbo.config.ReferenceConfig;
import com.alibaba.dubbo.config.RegistryConfig;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.lang.reflect.Method;


@Service
public class DubboServiceUtil {


    @Resource
    private Environment environment;


    public <T> T getOneDubboService(Class<T> tClass, String groupName, String applicationName, String ip, int port) {

        String url=null;
        if (ip != null) {
            StringBuilder stringBuilder=new StringBuilder(" dubbo://");
            stringBuilder.append(ip).append(":").append(port).append("/").append(tClass.getName()).append("?anyhost=true&application=").append(applicationName).append("&dubbo=2.0.2&interface=").append(tClass.getName()).append("&methods=");
        }
        Method[] methods = tClass.getMethods();
        String zookeeperAddress = environment.getProperty("dubbo.registry.address");

        return getDubboService(tClass, zookeeperAddress, applicationName, groupName, null);
    }

    public <T> T getDubboService(Class<T> tClass, String applicationName, String ip, int port) {
        return getDubboService(tClass, environment.getProperty("dubbo.registry.address"), applicationName, null, null);
    }

    /**
     * @param inf          接口位置  接口
     * @param zookeeperUrl zk地址 zookeeper://192.168.1.200:2181
     * @param appName      dubbo应用名称 dubbo.application.name
     * @param url          选填    url for per to per invoke  example dubbo://172.17.32.91:20880/org.apache.dubbo.demo.DemoService?anyhost=true&application=dubbo-demo-api-provider&dubbo=2.0.2&interface=org.apache.dubbo.demo.DemoService&methods=sayHello,sayHelloAsync&pid=32508&release=&side=provider&timestamp=1593253404714dubbo://172.17.32.91:20880/org.apache.dubbo.demo.DemoService?anyhost=true&application=dubbo-demo-api-provider&dubbo=2.0.2&interface=org.apache.dubbo.demo.DemoService&methods=sayHello,sayHelloAsync&pid=32508&release=&side=provider&timestamp=1593253404714
     * @return dubbo 服务
     * @throws ClassNotFoundException
     */
    public <T> T getDubboService(Class<T> inf, String zookeeperUrl, String appName, String group, String url) {
        ApplicationConfig application = new ApplicationConfig();
        application.setName(appName);
        RegistryConfig registryConfig = new RegistryConfig();
        registryConfig.setAddress(zookeeperUrl);

        ReferenceConfig rc = new ReferenceConfig();
        rc.setRegistry(registryConfig);
        rc.setApplication(application);
        rc.setGroup(group);
        rc.setInterface(inf);
        rc.setUrl(url);

        return (T) rc.get();

    }

}
